<script>
import { defineComponent, computed } from 'vue'
import { createNamespace, transformSize } from '../utils'
import { propsObject } from './props'
import FanAspectRatio from '../aspect-ratio/aspect-ratio.vue'

export default defineComponent({
  name: createNamespace('Image')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true
  },
  components: { FanAspectRatio },
  emits: ['click', 'longpress', 'load'],
  props: propsObject,
  setup(props, context) {
    const radiusStyle = computed(() => {
      return props.radius ? `border-radius:${transformSize(props.radius)};` : ''
    })
    const theStyle = computed(() => {
      return `overflow:hidden;position:relative;${radiusStyle.value}`
    })

    const aspectRatioNum = computed(() => (props.mode === 'widthFix' ? 0 : props.aspectRatio))
    // overflow:hidden 可能被修改，所以保险起见，圆角在这里也加上
    const imgStyle = computed(() => {
      const { height } = props
      const h = aspectRatioNum.value || height ? '100%' : transformSize(height)
      return `height:${h};${radiusStyle.value}`
    })
    const imgMode = computed(() => {
      const { height, mode } = props
      if (mode) return mode
      return !height ? 'widthFix' : 'scaleToFill'
    })

    const onClick = (e) => context.emit('click', e)
    const onLongpress = () => context.emit('longpress')
    const onLoad = (e) => context.emit('load', e)

    return { radiusStyle, theStyle, imgStyle, imgMode, aspectRatioNum, onClick, onLongpress, onLoad }
  }
})
</script>

<template>
  <FanAspectRatio :style="theStyle" :aspect-ratio="aspectRatioNum" :width="width" :height="height" @click="onClick">
    <div v-if="!src" :style="'height:100%;' + radiusStyle" class="fan-img--empty" :class="{ light: placeholderLight }">
    </div>
    <image v-else :style="imgStyle" class="fan-img" :src="src" :mode="imgMode"
      :show-menu-by-longpress="showMenuByLongpress" :lazy-load="lazyLoad" @longpress="onLongpress" @load="onLoad" />

    <slot />
  </FanAspectRatio>
</template>

<style lang="less">
@import './index.less';

// fix: 小程序图片有默认高度，会在 mode=widthFix 时由大到小抖动。由小到大（撑开式）好一些
.fan-img {
  height: 10px;
}
</style>
